package com.lzb.musicplayer.activity;

import android.media.AudioManager;
import android.view.View;
import android.widget.SeekBar;

import com.lzb.basic.utils.SPUtil;
import com.lzb.musicplayer.BaseAc;
import com.lzb.musicplayer.Content;
import com.lzb.musicplayer.R;
import com.lzb.musicplayer.audio.AudioPlayerManager;
import com.lzb.musicplayer.databinding.ActivityAudioBinding;
import com.lzb.musicplayer.receiver.BluetoothReceiver;
import com.lzb.musicplayer.receiver.HeadsetReceiver;

public class AudioActivity extends BaseAc<ActivityAudioBinding> implements View.OnClickListener {

    private AudioPlayerManager audioPlayerManager;

    @Override
    protected int onCreate() {
        return R.layout.activity_audio;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAudioBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        // 设置开关点击事件
        mDataBinding.ivOpenAlways.setOnClickListener(this);
        mDataBinding.ivOpenSeamless.setOnClickListener(this);
        mDataBinding.ivOpenAuto.setOnClickListener(this);
        mDataBinding.ivOpenBluetooth.setOnClickListener(this);
        mDataBinding.llEqualizer.setOnClickListener(this);

        // 设置SeekBar监听器
        mDataBinding.sbDuration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    SPUtil.putInt(mContext, Content.fadeDuration, progress);
                    mDataBinding.tvDuration.setText(progress + "s");
                    // 重新初始化音频播放器管理器以应用新设置
                    audioPlayerManager = AudioPlayerManager.getInstance(AudioActivity.this);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ivOpenAlways) {//始终播放
            toggleSwitch(Content.isOpenAlways, mDataBinding.ivOpenAlways);
        } else if (id == R.id.ivOpenSeamless) {
            toggleSwitch(Content.isOpenSeamless, mDataBinding.ivOpenSeamless);
        } else if (id == R.id.ivOpenAuto) {//自动播放
            toggleSwitch(Content.isOpenAuto, mDataBinding.ivOpenAuto);
            applyAutoPlaySettings();
        } else if (id == R.id.ivOpenBluetooth) {//蓝牙播放
            toggleSwitch(Content.isOpenBluetooth, mDataBinding.ivOpenBluetooth);
            applyBluetoothSettings();
        } else if (id == R.id.llEqualizer) {//均衡器
            startActivity(EqualizerActivity.class);
        }
    }

    @Override
    protected void initData() {
        // 初始化音频播放器管理器
        audioPlayerManager = AudioPlayerManager.getInstance(this);

        // 初始化开关状态
        updateSwitchStates();
        int duration = SPUtil.getInt(mContext, Content.fadeDuration, 7);
        mDataBinding.sbDuration.setProgress(duration);
        mDataBinding.tvDuration.setText(duration + "s");

        // 应用耳机和蓝牙自动播放设置（需要注册广播接收器）
        applyAutoPlaySettings();
        applyBluetoothSettings();
    }

    /**
     * 更新所有开关的UI状态
     */
    private void updateSwitchStates() {
        boolean isAlwaysOpen = SPUtil.getBoolean(this, Content.isOpenAlways, false);
        boolean isSeamlessOpen = SPUtil.getBoolean(this, Content.isOpenSeamless, false);
        boolean isAutoOpen = SPUtil.getBoolean(this, Content.isOpenAuto, false);
        boolean isBluetoothOpen = SPUtil.getBoolean(this, Content.isOpenBluetooth, false);

        mDataBinding.ivOpenAlways.setImageResource(isAlwaysOpen ? R.drawable.kai : R.drawable.guan);
        mDataBinding.ivOpenSeamless.setImageResource(isSeamlessOpen ? R.drawable.kai : R.drawable.guan);
        mDataBinding.ivOpenAuto.setImageResource(isAutoOpen ? R.drawable.kai : R.drawable.guan);
        mDataBinding.ivOpenBluetooth.setImageResource(isBluetoothOpen ? R.drawable.kai : R.drawable.guan);
    }

    /**
     * 切换开关状态
     *
     * @param key       SP存储的key
     * @param imageView 开关图片控件
     */
    private void toggleSwitch(String key, android.widget.ImageView imageView) {
        boolean currentState = SPUtil.getBoolean(this, key, false);
        boolean newState = !currentState;

        // 保存新的状态
        SPUtil.putBoolean(this, key, newState);

        // 更新UI
        imageView.setImageResource(newState ? R.drawable.kai : R.drawable.guan);
    }

    /**
     * 应用淡入淡出设置（现在由SeekBar监听器处理）
     */
    private void applyFadeSettings() {
        int fadeDuration = SPUtil.getInt(mContext, Content.fadeDuration, 7);
        // 音频播放器管理器会在初始化时自动加载设置
        // 这里只需要更新UI显示
        mDataBinding.sbDuration.setProgress(fadeDuration);
        mDataBinding.tvDuration.setText(fadeDuration + "s");
    }

    /**
     * 应用自动播放设置（耳机插入时）
     */
    private void applyAutoPlaySettings() {
        boolean isAutoPlay = SPUtil.getBoolean(mContext, Content.isOpenAuto, false);
        if (isAutoPlay) {
            // 注册耳机插拔广播接收器
            registerHeadsetReceiver();
        } else {
            // 注销耳机插拔广播接收器
            unregisterHeadsetReceiver();
        }
    }

    /**
     * 应用蓝牙播放设置
     */
    private void applyBluetoothSettings() {
        boolean isBluetoothPlay = SPUtil.getBoolean(mContext, Content.isOpenBluetooth, false);
        if (isBluetoothPlay) {
            // 注册蓝牙连接广播接收器
            registerBluetoothReceiver();
        } else {
            // 注销蓝牙连接广播接收器
            unregisterBluetoothReceiver();
        }
    }

    // 耳机广播接收器相关
    private HeadsetReceiver headsetReceiver;

    /**
     * 注册耳机插拔广播接收器
     */
    private void registerHeadsetReceiver() {
        if (headsetReceiver == null) {
            headsetReceiver = new HeadsetReceiver();
            headsetReceiver.setOnHeadsetStateChangedListener(new HeadsetReceiver.OnHeadsetStateChangedListener() {
                @Override
                public void onHeadsetConnected() {
                    // 耳机插入，自动播放
                    if (audioPlayerManager != null && !audioPlayerManager.isPlaying()) {
                        audioPlayerManager.togglePlayback();
                    }
                }

                @Override
                public void onHeadsetDisconnected() {
                    // 耳机拔出，可以暂停播放（可选）
                    // if (audioPlayerManager != null && audioPlayerManager.isPlaying()) {
                    //     audioPlayerManager.togglePlayback();
                    // }
                }
            });
            headsetReceiver.register(this);
        }
    }

    /**
     * 注销耳机插拔广播接收器
     */
    private void unregisterHeadsetReceiver() {
        if (headsetReceiver != null) {
            headsetReceiver.unregister(this);
            headsetReceiver = null;
        }
    }

    // 蓝牙广播接收器相关
    private BluetoothReceiver bluetoothReceiver;

    /**
     * 注册蓝牙连接广播接收器
     */
    private void registerBluetoothReceiver() {
        if (bluetoothReceiver == null) {
            bluetoothReceiver = new BluetoothReceiver();
            bluetoothReceiver.setOnBluetoothStateChangedListener(new BluetoothReceiver.OnBluetoothStateChangedListener() {
                @Override
                public void onBluetoothConnected() {
                    // 蓝牙设备连接，自动播放
                    if (audioPlayerManager != null && !audioPlayerManager.isPlaying()) {
                        audioPlayerManager.togglePlayback();
                    }
                }

                @Override
                public void onBluetoothDisconnected() {
                    // 蓝牙设备断开，可以暂停播放（可选）
                    // if (audioPlayerManager != null && audioPlayerManager.isPlaying()) {
                    //     audioPlayerManager.togglePlayback();
                    // }
                }
            });
            bluetoothReceiver.register(this);
        }
    }

    /**
     * 注销蓝牙连接广播接收器
     */
    private void unregisterBluetoothReceiver() {
        if (bluetoothReceiver != null) {
            bluetoothReceiver.unregister(this);
            bluetoothReceiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        unregisterHeadsetReceiver();
        unregisterBluetoothReceiver();
    }
}